package spring.cloud.tasks.executor.utils.zookeeper;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import spring.cloud.tasks.executor.utils.SystemEnvProperties;

/**
 * 基于Zookeeper的注册中心配置.
 */
@Slf4j
@Setter
@Getter
public class NameSpaceConfiguration {


    public static final int MIN_RETRY_TIMES = 3;
    /**
     * 连接Zookeeper服务器的列表. 包括IP地址和端口号. 多个地址用逗号分隔. 如: host1:2181,host2:2181
     */
    private String connectString;
    /**
     * 命名空间.
     */
    private String namespace;
    /**
     * 连接超时时间. 单位毫秒.
     */
    private int connectionTimeoutMs;
    /**
     * 会话超时时间. 单位毫秒.
     */
    private int sessionTimeoutMs;
    /**
     * 等待重试的间隔时间的初始值. 单位毫秒.
     */
    private int baseSleepTimeMs;
    /**
     * 最大重试次数.
     */
    private int maxRetries;
    /**
     * 等待重试的间隔时间的最大值. 单位毫秒.
     */
    private int maxSleepMs;


    /**
     * 连接Zookeeper的权限令牌. 缺省为不需要权限验证.
     */
    private String digest;

    public NameSpaceConfiguration() {

    }

    /**
     * 包含了必需属性的构造器.
     *
     * @param connectString   连接Zookeeper服务器的列表
     * @param namespace       命名空间
     * @param baseSleepTimeMs 等待重试的间隔时间的初始值
     * @param maxRetries      最大重试次数
     * @param maxSleepMs      等待重试的间隔时间的最大值
     */
    public NameSpaceConfiguration(final String connectString, final String namespace, final int baseSleepTimeMs, final int maxRetries, final int maxSleepMs) {
        this.connectString = connectString;
        this.namespace = namespace;
        this.baseSleepTimeMs = baseSleepTimeMs;
        this.maxRetries = maxRetries;
        this.maxSleepMs = maxSleepMs;
    }

    public NameSpaceConfiguration(final String connectString, final String namespace, final int baseSleepTimeMs, final int maxSleepMs) {
        this.connectString = connectString;
        this.namespace = namespace;
        this.baseSleepTimeMs = baseSleepTimeMs;
        this.maxSleepMs = maxSleepMs;
        this.maxRetries = maxRetries();
    }

    private int maxRetries() {
        int maxRetries = -1;
        if (SystemEnvProperties.VIP_SATURN_ZK_CLIENT_RETRY_TIMES != -1) {
            maxRetries = SystemEnvProperties.VIP_SATURN_ZK_CLIENT_RETRY_TIMES;
        } else if (SystemEnvProperties.VIP_SATURN_USE_UNSTABLE_NETWORK_SETTING) {
            maxRetries = SystemEnvProperties.VIP_SATURN_RETRY_TIMES_IN_UNSTABLE_NETWORK;
        }

        return maxRetries > NameSpaceConfiguration.MIN_RETRY_TIMES ? maxRetries : NameSpaceConfiguration.MIN_RETRY_TIMES;
    }


}
